package com.gzc.net
{
	import flash.utils.Dictionary;
	
	import mx.messaging.ChannelSet;
	import mx.messaging.Consumer;
	import mx.messaging.channels.AMFChannel;
	import mx.messaging.channels.StreamingAMFChannel;
	import mx.messaging.events.MessageAckEvent;
	import mx.messaging.events.MessageEvent;
	import mx.messaging.events.MessageFaultEvent;

	/**
	 * 
	 * @author gzc
	 * 
	 * 使用Dic存储Consumer对象
	 * 
	 * 使用方法，
	 * 
	 */ 
	public class ConsumerFactory
	{
		private static var _instance:ConsumerFactory = null;
		
		public static function getInstance():ConsumerFactory{
			if(_instance == null) {
				_instance = new ConsumerFactory();
			}
			return _instance;
		}
		
		private var _consumerDic:Dictionary = new Dictionary();
		private var _channelset:ChannelSet = new ChannelSet();
		private var _contextUrl:String = "";
		
		public function init(url:String):void{
			if(url.charAt(url.length - 1) != '/') {
				url += '/';
			}
			var streamingAMFChannel:StreamingAMFChannel = new StreamingAMFChannel();
			streamingAMFChannel.url = url + "messagebroker/streamingamf";
			_channelset.addChannel(streamingAMFChannel);
			var amfChannel:AMFChannel = new AMFChannel();
			amfChannel.url = url + "messagebroker/amf";
			_channelset.addChannel(amfChannel);
		}
		
		public function get initialized():Boolean{
			return _channelset.channels.length > 0;
		}
		
		protected function beginSubscribe(status:String):void {
			
		}
		
		protected function endSubscribe(status:String):void{
			
		}
		
		private function _getConsumer(name:String):Consumer {
			var consumer:Consumer = _consumerDic[name];
			if(consumer == null) {
				consumer = new Consumer();
				consumer.channelSet = _channelset;
				consumer.destination = name;
				
				_consumerDic[name] = consumer;
			}
			return consumer;					
		}
		
		public function subscribe(destination:String, resultHandler:Function, status:String,
									 selector:String=null, clientId:String=null):void{
			
			beginSubscribe(status);
			
			var consumer:Consumer = _getConsumer(destination);
			
			if(selector) consumer.selector = selector;
			consumer.addEventListener(MessageEvent.MESSAGE, _onMessage);
			consumer.addEventListener(MessageAckEvent.ACKNOWLEDGE, _onAcknowledge);
			consumer.addEventListener(MessageFaultEvent.FAULT, _onFault);
			consumer.subscribe(clientId);
			
			function _onMessage(e:MessageEvent):void{
				trace('message recieved!');
				resultHandler(e);
			}
			
			function _onAcknowledge(e:MessageAckEvent):void{
				trace(e.message.toString());
			}
			
			function _onFault(e:MessageFaultEvent):void {				
				trace(e.message.toString());
			}
		}
		
		public function unSubscribe(destination:String, preserveDurable:Boolean=false):void{
			var consumer:Consumer = _consumerDic[destination];
			if(consumer){
				consumer.unsubscribe(preserveDurable);
			}
			
			_consumerDic[destination] = null;
		}
		
	}
}